// \u4e00-\u9fa5] 中文验证规则
import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  data: {
    point: '',
    building: '',
    room: '',
    name: '',
    gender: '0',
    mobile: '',
    idcardFrontUrl: '',
    idcardBackUrl: '',
  },
  onLoad({ point, building, room }) {
    // 获取房屋信息数据
    this.setData({
      point,
      building,
      room,
    })
  },
  rules: {
    name: [
      {
        required: true,
        message: '业主姓名不能为空!',
      },
      {
        pattern: /^[\u4e00-\u9fa5]{2,5}$/,
        message: '业主姓名只能为中文!',
      },
    ],
    mobile: [
      {
        required: true,
        message: '业主手机号不能为空!',
      },
      {
        pattern: /^1[3-8]\d{9}$/,
        message: '请填写正确的手机号!',
      },
    ],
    idcardFrontUrl: [
      {
        required: true,
        message: '请上传身份证照片面!',
      },
    ],
    idcardBackUrl: [
      {
        required: true,
        message: '请上传身份证国徽面!',
      },
    ],
  },
  async submitForm() {
    if (!this.validate()) return //获取全部的数据（剔除__webviewId__）
    const { __webviewId__, ...data } = this.data
    console.log(__webviewId__) //调用接口
    const res = await wx.http.post('/room', data)
    console.log(res)
    console.log(res.code) //检测是否成功
    if (res.code !== 10000) return wx.utils.toast(res.message) //返回房屋列表页面
    wx.navigateBack({
      delta: 4,
    })
  },
  async uploadPicture(ev) {
    const type = ev.mark.type
    try {
      //打开相册或者拍照
      const media = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'],
      }) //调用api上传照片
      wx.uploadFile({
        filePath: media.tempFiles[0].tempFilePath,
        url: wx.http.baseURL + '/upload',
        name: 'file',
        header: {
          Authorization: 'Bearer ' + getApp().token,
        },
        success: (result) => {
          //处理返回的json数据
          const data = JSON.parse(result.data)
          if (data.code !== 10000) return wx.utils.toast('上传图片失败') //渲染数据
          this.setData({
            [type]: data.data.url,
          })
        },
      })
    } catch (error) {
      console.log(error)
    }
  },
})
